﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Diagnostics.Contracts;
using ShredTheLog.Api.DataContracts;
using System.ComponentModel.Composition;
using ShredTheLog.Api;

namespace ShredTheLog.Converters
{
    [ValueConversion(typeof(Country), typeof(string))]
    public sealed class CountryConverter : ConverterBase, IValueConverter
    {
        [Import]
        private IShredServices ShredServices { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            // Не знаю почему, но сюда иногда сваливается null
            if (value != null)
                return Convert((Country)value);
            else
                return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        private const Country DeletedUsersCountry = (Country)0;

        public string Convert(Country v)
        {
            Contract.Ensures(!String.IsNullOrWhiteSpace(Contract.Result<string>()));

            if (v == DeletedUsersCountry)
                return "-";

            Type enumType = v.GetType();
            string key = String.Format("s_{0}_{1}", enumType.Name, Enum.GetName(enumType, v));
            Contract.Assume(!String.IsNullOrWhiteSpace(key));
            var result = ShredServices.GetLocalizedString(key);
            Contract.Assume(!String.IsNullOrWhiteSpace(result));
            return result;
        }

        public static readonly CountryConverter Default = new CountryConverter();
    }
}
